# -*- coding: utf-8 -*-
import traceback

from flask import current_app as app
from flask import flash, session, redirect, url_for, request, abort
from flask.blueprints import Blueprint
from sqlalchemy.sql.expression import and_
from flask.helpers import send_file, jsonify


from sys2do.views import BasicView
from sys2do.util.decorator import templated, loginRequired, activetab, myjson
from sys2do.util.common import _g
from sys2do.constant import TAB_HOME, PO_NEW, IVTNT_NEW, TNS_NEW, \
    ACTIVE, FIN_NEW, FIN_IN, FIN_OUT, MESSAGE_ERROR, \
    MSG_NO_ID_SUPPLIED, MSG_SERVER_ERROR, SO_NEW, MSG_NOT_ALL_PARAMS_OK
from sys2do.util.logic_helper import getPermission, getCurrentShopProfile
from sys2do.model import qry, SO, PO, InventoryNote, DN, FinNote, SysFile, SysDict, Shop
from sys2do.util.tpl_func import getMaster



__all__ = ['bpRoot']

bpRoot = Blueprint( 'bpRoot', __name__ )

class RootView( BasicView ):

    @templated( "index.html" )
    @activetab( TAB_HOME )
    @loginRequired
    def index( self ):
        spobj = getCurrentShopProfile()
        todo = {}
        if getPermission( 'PURCHASE_APPROVE' ):
            todo['PURCHASE_APPROVE'] = qry( PO ).filter( and_( PO.active == ACTIVE,
                                                               PO.status == PO_NEW,
                                                               PO.shopID == spobj.shopID,
                                                                ) )
        if getPermission( 'SALE_APPROVE' ):
            todo['SALE_APPROVE'] = qry( SO ).filter( and_( SO.active == ACTIVE,
                                                           SO.status == SO_NEW,
                                                           SO.shopID == spobj.shopID, ) )
        if getPermission( 'INVENTORY_NOTE_APPROVE' ):
            todo['INVENTORY_NOTE_APPROVE'] = qry( InventoryNote ).filter( and_( InventoryNote.active == ACTIVE,
                                                                                InventoryNote.shopID == spobj.shopID,
                                                                                InventoryNote.status == IVTNT_NEW,
                                                                                ) )

        if getPermission( 'DN_APPROVE' ):
            todo['DN_APPROVE'] = qry( DN ).filter( and_( DN.active == ACTIVE,
                                                         DN.status == TNS_NEW,
                                                         DN.sShopID == spobj.shopID, ) )
        if getPermission( 'FIN_IN_APPROVE' ):
            todo['FIN_IN_APPROVE'] = qry( FinNote ).filter( and_( FinNote.active == ACTIVE,
                                                                  FinNote.status == FIN_NEW,
                                                                  FinNote.direction == FIN_IN,
                                                                  FinNote.shopID == spobj.shopID ) )
        if getPermission( 'FIN_OUT_APPROVE' ):
            todo['FIN_OUT_APPROVE'] = qry( FinNote ).filter( and_( FinNote.active == ACTIVE,
                                                                   FinNote.status == FIN_NEW,
                                                                   FinNote.direction == FIN_OUT,
                                                                   FinNote.shopID == spobj.shopID ) )

        return {'todo' : todo,
                'canSale' : spobj.canSale == 0,
                'canPurchase' : spobj.canPurchase == 0,
                }


    @loginRequired
    def switch( self ):
        sid = _g( 'id' )
        if sid:
            session['currentShopID'] = sid
        return redirect( url_for( 'bpRoot.view' ) )


    def goto( self ):
        q = _g( 'q' )

        if not q :
            url = request.args.get( 'next' ) or request.referrer or url_for( '.view' )
            return redirect( url )

        if not q.isdigit():
            flash( MSG_NOT_ALL_PARAMS_OK, MESSAGE_ERROR )
            return redirect( url_for( "bpRoot.view" ) )

        try:
            pre = qry( SysDict ).filter( and_( SysDict.type == 'OBJECT_PREFIX', SysDict.value == q[:3] ) ).one()
            import sys2do.model as model
            clz = getattr( model, pre.name )
            obj = qry( clz ).filter( clz.no == q ).one()
        except:
            traceback.print_exc()
            flash( MSG_NOT_ALL_PARAMS_OK, MESSAGE_ERROR )
            return redirect( url_for( "bpRoot.view" ) )
        else:
            return redirect( obj.viewURL() )





    def dl( self ):
        fid = _g( 'id' )
        if not fid : abort( 404 )
        obj = qry( SysFile ).get( fid )
        if not obj : abort( 404 )
        return send_file( obj.realPath, as_attachment = True, attachment_filename = obj.name )


    def mi( self ):
        mid = _g( 'mid' )
        if not mid:
            return jsonify( {'code' : 1, 'msg' : MSG_NO_ID_SUPPLIED} )
        try:
            result = [{'id' : m.id, 'val' : unicode( m )} for m in getMaster( mid )]
            return jsonify( {'code' : 0, 'data' : result } )
        except:
            traceback.print_exc()
            return jsonify( {'code' : 1 , 'msg' : MSG_SERVER_ERROR} )




bpRoot.add_url_rule( '/', view_func = RootView.as_view( 'view' ), defaults = {'action':'index'} )
bpRoot.add_url_rule( '/favicon.ico', view_func = lambda : redirect( url_for( 'static', filename = 'favicon.ico' ) ) )
bpRoot.add_url_rule( '/robots.txt', view_func = lambda : redirect( url_for( 'static', filename = 'robots.txt' ) ) )
bpRoot.add_url_rule( '/<action>', view_func = RootView.as_view( 'view' ) )
